import { Message } from 'element-ui';
import Api from '@/api';
import router from '@/router';
import _ from 'lodash';
import { getMenuData, getPermissionRouteList } from '@/menus';
import { noNeedPermissionRouteNames } from '@/constants';

// 加载modules
function mountModules() {
  const files = require.context('./modules', true, /\.js$/);
  const fileNames = files.keys();
  let modules = {};
  fileNames.forEach(item => {
    const paths = item.split('/');
    const namespace = paths.slice(1, paths.length);
    const path = namespace.join('.modules.').replace(/\.js$/, '');
    _.set(modules, path, files(item).default);
    let temp = [];
    namespace.forEach(name => {
      temp.push(name);
      const path = temp.join('.modules.').replace(/\.js$/, '');
      _.set(modules, path + '.namespaced', true);
    });
  });
  return modules;
}
//是否有权限
function pathMatch(path, menus = []) {
  if (menus && menus.length) {
    if (menus.some(item => new RegExp(`${item.path}$`).test(path))) {
      return true;
    } else {
      const children = menus.map(item => item.children || []).flat();
      return pathMatch(path, children);
    }
  } else {
    return false;
  }
}

export default {
  state: {
    menuData: getMenuData(),
    permissionRouteList: getPermissionRouteList(),
    globalLoading: false,
  },
  mutations: {
    setState(state, payload) {
      const keys = Object.keys(payload) || [];
      keys.forEach(key => {
        state[key] = payload[key];
      });
    },
  },
  actions: {
    async checkPermission({ state, dispatch, commit }, route) {
      const { name, path } = route || router.currentRoute;
      if (noNeedPermissionRouteNames.includes(name)) {
        return true;
      }
      return pathMatch(path, state.permissionRouteList || []);
    },
    async authCheck({ dispatch, state, commit }, route) {
      const isLogin = await dispatch('user/checkUserInfo').catch(e => {
        console.log(e);
      });
      if (!isLogin) {
        return { isLogin: false };
      }
      const isAllow = await dispatch('checkPermission', route);

      commit('setState', {
        globalLoading: false,
      });
      return {
        isLogin,
        isAllow,
      };
    },
  },
  modules: mountModules(),
};
